from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
import json
from django.contrib.auth import authenticate, login, logout
from django.http.response import HttpResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest.serializers import UserSerializer
from rest_framework.authtoken.models import Token
import copy
from datetime import datetime

def func_login(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    data = {
        'msg': '1',
        'data': {}
    }
    if user is not None:
        if user.is_active:
            login(request, user)
            token, _ = Token.objects.get_or_create(user=user)
            data['msg'] = '0'
            data['data'] = {
                'id': user.id,
                'name': user.username,
                'authToken': token.key
            }
            return HttpResponse(json.dumps(data))
    return HttpResponse(json.dumps(data))


def func_logout(request):
    logout(request)
    return HttpResponse('')


class UserSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    serializer_class = UserSerializer

    def get_queryset(self):
        kwargs = {}
        if 'keyword' in self.request.GET and self.request.GET['keyword'] != "":
            kwargs['username__contains'] = self.request.GET['keyword']
        ft = User.objects.filter(**kwargs).order_by('-id')
        return ft

    def create(self, request):
        username = request.POST.get('username')
        password =  request.POST.get('password')
        email =  request.POST.get('email','')
        is_staff = request.POST.get('is_staff',False)
        data = {
            'username':username,
            'email':email,
            'is_staff':is_staff
        }
        user = User.objects.create(**data)
        user.set_password(password)
        user.save()

        return Response('ok')
